package ui

import (
	"fmt"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/data/binding"
	"fyne.io/fyne/v2/widget"
	"time"
)

type GameTime struct {
	blackTimeLabel *widget.Label
	whiteTimeLabel *widget.Label
	blackIcon      *widget.Icon
	whiteIcon      *widget.Icon
	blackTime      binding.String
	whiteTime      binding.String
}

func NewGameTime() *GameTime {
	blackTime := binding.NewString()
	whiteTime := binding.NewString()
	_ = blackTime.Set("00:00")
	_ = whiteTime.Set("00:00")
	blackTimeLabel := widget.NewLabelWithData(blackTime)
	whiteTimeLabel := widget.NewLabelWithData(whiteTime)

	blackIcon := widget.NewIcon(fyne.NewStaticResource("black.png", blackChessSource))
	whiteIcon := widget.NewIcon(fyne.NewStaticResource("white.png", whiteChessSource))

	return &GameTime{
		blackTimeLabel: blackTimeLabel,
		whiteTimeLabel: whiteTimeLabel,
		blackIcon:      blackIcon,
		whiteIcon:      whiteIcon,
		blackTime:      blackTime,
		whiteTime:      whiteTime,
	}
}

func (gt *GameTime) SetBlackTime(t time.Duration) {
	_ = gt.blackTime.Set(formatTimeDuration(t))
	gt.blackTimeLabel.SetText(fmt.Sprintf("Black: %02d:%02d", int(t.Minutes()), int(t.Seconds())%60))
}

func (gt *GameTime) SetWhiteTime(t time.Duration) {
	_ = gt.whiteTime.Set(formatTimeDuration(t))
	gt.whiteTimeLabel.SetText(fmt.Sprintf("White: %02d:%02d", int(t.Minutes()), int(t.Seconds())%60))
}

func (gt *GameTime) GetWidget() fyne.CanvasObject {
	return container.NewHBox(gt.blackIcon, gt.blackTimeLabel, gt.whiteIcon, gt.whiteTimeLabel)
}

func (gt *GameTime) Reset() {
	gt.SetBlackTime(0)
	gt.SetWhiteTime(0)
}

func formatTimeDuration(duration time.Duration) string {
	return fmt.Sprintf("%02d:%02d", int(duration.Minutes()), int(duration.Seconds())%60)
}
